/**
 * NoxCanvas:Image
 *  
 * @author Lukas Krocek
 * @copyright 2011 - 2012
 * 
 * @param url string - url of image
 * @param frames int - count of frames on row in image
 * @param pos Object - default position {x: <int>, y: <int>}
 * @param time int - time of cycle in miliseconds
 * @param reverse bool|void - on end of frame cycle will be animated backward insted of new start cycle
 **/
function NoxImage (url, frames, pos, time, reverse) {

	/** @var float frame x and y positions */
	var fX = 0,
		fY = 0,
		/** @var float image x and y positions */
	    posX = 0,
	    posY = 0,
	    /** @var int height and width of frame */
	    fWidth = 0,
	    fHeight = 0,
	    /** @var int height and width of image */
	    height = 0,
	    width = 0,
	    
		/** @var bool image ready state */
	    isReady = false,
    
	    /** @var int repeat interval for re-rendering */
	    fTime = Math.round((time === undefined ? 1000 : time) / frames),
    
	    /** @var Image */
	    image = new Image();
    if (typeof(reverse) === "boolean") {
    	reverse = 1;
    }
    image.src = url;
    
    // setup default position
    if (typeof(pos) === 'object') {
    	posX = pos.x;
    	posY = pos.y;
    }
    this.imageOnLoad = function (e) {
		// setup image properties to object
		width = this.width;
		height = this.height;
		fWidth = this.width / frames;
		fHeight = this.height;
		isReady = true;
	};
	image.addEventListener('load',this.imageOnLoad,false);
	return {
		/**
		 * calculate next frame positions for animation cycle
		 */
	    animate: function () {
	    	if (typeof (reverse) == "number") {
	    		var newWidth = (fX + (reverse * fWidth));
			    if (newWidth >= width) {
			    	reverse = -1;
			    } else if (newWidth <= 0) {
			    	reverse = 1;
			    }
			    fX += (reverse * fWidth);
	    	} else {
			    fX += fWidth;
			    if (fX >= width) fX = 0;
		    }
		},
		isReady: function () {
			return isReady;
		},
		
		/**
		 * Render image
		 * 
		 * @param ctx CanvasContext - by canvas.getContext('2d')
		 */
		render: function (ctx) {
		    ctx.drawImage(image, fX, fY, fWidth, fHeight, posX, posY, fWidth, height);
		},
	
		/**
		 * Move image on position
		 * 
		 * @param x int - X poisition
		 * @param y int - Y poisition
		 */
		move: function (x, y) {
		    posX += x;
		    posY += y;
		},
	
		/**
		 * Return a frame interval
		 * 
		 * @return int|false
		 */
		getInterval: function () {
			return (fTime === 1000 ? false : fTime);
		}
	
	};
}

